#!/usr/bin/python2

import os, sys
lib_path = os.path.abspath('./PyPDF2')
sys.path.append(lib_path)

from PyPDF2 import PdfFileWriter, PdfFileReader

numInputs = len(sys.argv) - 2

if (numInputs < 1):
	print "Please specify as arguments one or more input file names and an output file name"
	sys.exit(1)

output = PdfFileWriter()
inputs = []
for i in range(0, numInputs):
	path = sys.argv[1 + i]
	print "Reading:", path
	reader = PdfFileReader(open(path, "rb"))
	inputs.append(reader)

numPages = 0
for i in range(0, numInputs):
	numPages = max(numPages, inputs[i].getNumPages())

# add pages
for p in range(0, numPages):
	print "Writing page", p
	page = None
	for i in range(0, numInputs):
		if p < inputs[i].getNumPages():
			if not page:
				page = inputs[i].getPage(p)
			else:
				page.mergePage(inputs[i].getPage(p))
	output.addPage(page)

# write "output"
path = sys.argv[1 + numInputs]
print "Writing:", path
outputStream = file(path, "wb")
output.write(outputStream)
